# coding: utf-8
from flask import request

from app.api.ip_utils import ip_util
from app.api_v2.constant import PER_PAGE
from app.api_v2.views import Response
from app.op.models import Area


def ip_to_area(remote_ip):
    """
    create by ld_wu 2017-11-20
    ip转换为省份及城市对象
    :param remote_ip:
    :return:
    """
    ip_info = ip_util.find(remote_ip)
    try:
        code = str(int(ip_info[2])) if ip_info.any() else '110000'
    except:
        code = '110000'

    city = Area.get_by_id(code[:4] + '00')
    prov = Area.get_by_id(code[:2] + '0000')

    return prov, city


class Pagination(object):

    def __init__(self, query, schema=None):
        incoming = request.args
        self.page = incoming.get("page", type=int, default=1)
        self.per_page = incoming.get('per_page', type=int, default=PER_PAGE)
        self.query = query
        self.schema = schema

        self.paginate = query.paginate(self.page, self.per_page)

    @property
    def current(self):
        """
        返回当前页码
        :return:
        """
        return self.page

    @property
    def pages(self):
        """
        页数
        :return:
        """
        return self.paginate.pages

    @property
    def total(self):
        """
        条目数
        :return:
        """
        return self.paginate.total

    @property
    def items(self):
        """
        获取分页数据
        :return:
        """
        return self.paginate.items

    def to_response(self, items):
        data, errors = self.schema.dump(items)
        return Response(
            body={
                'list': data,
                'pages': self.pages,
                'total': self.total,
                'current': self.current
            }
        )

    @classmethod
    def get_pagination_response(cls, query, schema):
        """
        add by chenhj
        返回分页json数据
        :param query: SQLAlchemy对象
        :param schema: DB 对应schema对象
        :return:
        """
        paginate_obj = cls(query)
        data, errors = schema.dump(paginate_obj.items)
        return Response(
            body={
                'list': data,
                'pages': paginate_obj.pages,
                'total': paginate_obj.total,
                'current': paginate_obj.current
            }
        )